<template>
  <div class="app-container">
    <el-row :gutter="10">
      <!--树结构-->
      <!--      <el-col>-->
      <!--        <span class="note">*1.器具的所属范围为 每个试验室（待修改）</span>-->
      <!--      </el-col>-->
      <el-col :span="4" :xs="24">
        <div class="app-container-tree-border">
          <el-input v-model="syTypeName" placeholder="请输入器具名称" clearable size="small" prefix-icon="el-icon-search" />
          <el-tree
            class="input-tree"
            :data="options"
            :props="defaultProps"
            default-expand-all
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="tree"
            node-key="id"
            highlight-current
            @node-click="handleNodeClick"
          >
            <div slot-scope="{ node, data }" class="custom-tree-node" :title="node.label" v-text="node.label"></div>
          </el-tree>
        </div>
      </el-col>

      <el-col :span="20" :xs="24">
        <div class="app-container-table-border">
          <div v-show="oneShow">
            <el-row style="margin-bottom: 55px"></el-row>
            <el-table border stripe v-loading="loading" :data="baQjDetailList">
              <el-table-column label="序号" type="index" align="center" />
              <el-table-column label="上级" align="center" prop="parentName" :show-overflow-tooltip="true" />
              <el-table-column label="器具名称" align="center" prop="syQjName" :show-overflow-tooltip="true" />
            </el-table>

            <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />
          </div>
          <div v-show="twoShow">
            <el-row :gutter="10" class="mb8 top-right-btn sycs-add">
              <el-col :span="1.5">
                <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button type="info" plain icon="el-icon-upload2" size="mini" @click="handleImport">导入</el-button>
              </el-col>
            </el-row>
            <el-table border stripe v-loading="loading" :data="baQjDetailList" table-layout="auto" style="white-space: nowrap">
              <el-table-column label="序号" type="index" align="center" width="60" />
              <el-table-column label="盒（筒）号" align="center" prop="hh" min-width="120" :show-overflow-tooltip="true" />
              <el-table-column label="类别" align="center" prop="syQjName" width="100" :show-overflow-tooltip="true" />
              <el-table-column label="质量（g）" align="center" prop="quality" width="100" :show-overflow-tooltip="true" />
              <el-table-column label="筒容积（cm3）" align="center" prop="tongrj" width="120" :show-overflow-tooltip="true" v-if="currentNode.label && currentNode.label.indexOf('筒') != -1" />
              <el-table-column label="标定日期" align="center" prop="htime" width="140" :show-overflow-tooltip="true">
                <template slot-scope="scope">{{ parseTime(scope.row.htime, "{y}-{m}-{d}") }}</template>
              </el-table-column>
              <el-table-column label="标定人员" align="center" prop="hper" width="100" :show-overflow-tooltip="true" />
              <el-table-column label="备注" align="center" prop="remark" width="120" :show-overflow-tooltip="true" />
              <el-table-column label="状态" align="center" prop="status" width="120" :show-overflow-tooltip="true" />
              <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="120">
                <template slot-scope="scope">
                  <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">修改</el-button>
                  <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>

            <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />
          </div>
        </div>
      </el-col>
    </el-row>
    <!-- 用户导入对话框 -->
    <jy-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?deptId=' + deptId + '&qjId=' + queryParams.qjId"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip"><el-checkbox v-model="upload.updateSupport" />是否更新已经存在的用户数据</div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline" @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" type="primary" @click="submitFileForm">确 定</el-button>
        <el-button size="small" @click="upload.open = false">取 消</el-button>
      </div>
    </jy-dialog>
    <ba-qj-detail-add-or-update ref="addOrUpdateRef" :current-node="currentNode" @callBack="handleQuery" />
  </div>
</template>

<script>
import { getBaQjDetail, delBaQjDetail, addBaQjDetail, updateBaQjDetail, qjTree, pageSub, page, qjList } from "@/api/sycs/baQjDetail";
import store from "@/store";
import { biList } from "@/api/sycs/bsJudgeBase";
import { mapGetters } from "vuex";
import BaQjDetailAddOrUpdate from "./BaQjDetailAddOrUpdate.vue";
import { getToken } from "@/utils/auth";

export default {
  components: { BaQjDetailAddOrUpdate },
  name: "BaQjDetail",
  data() {
    return {
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 器具明细表表格数据
      baQjDetailList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        qjId: undefined,
        remark: undefined,
        hh: undefined
      },
      syTypeName: undefined,
      options: [],
      defaultProps: {
        children: "children",
        label: "label"
      },
      // 当前树节点
      currentNode: {},
      oneShow: false, // 点击树显示子表
      twoShow: false, // 点击显示详情表
      qjList: [], // 器具类别列表
      defaultDate: new Date(), // 默认当前系统时间
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/sycs/baQjDetail/importData"
      }
    };
  },
  created() {
    this.getDeptTree();
    this.getQjList();
  },
  computed: {
    ...mapGetters(["deptId"])
  },
  watch: {
    deptId(newValue, oldValue) {
      this.deptId = newValue;
      console.log("-----------deptId-----------", this.deptId);
    },
    // 根据名称筛选树
    syTypeName(val) {
      this.$refs.tree.filter(val);
    }
  },
  methods: {
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 查询器具明细表列表 */
    getList() {
      if (!this.deptId) {
        this.$alert("", "请选择试验室", {
          confirmButtonText: "确定",
          type: "warning",
          center: true
        });
        return;
      }
      this.loading = true;
      this.queryParams = {
        ...this.queryParams,
        deptId: this.deptId
      };
      page(this.queryParams).then((response) => {
        this.baQjDetailList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询树结构 */
    getDeptTree() {
      qjTree().then((response) => {
        this.options = response.data;
      });
    },
    getTreeList() {
      if (!this.deptId) {
        this.$alert("", "请选择试验室", {
          confirmButtonText: "确定",
          type: "warning",
          center: true
        });
        return;
      }
      this.loading = true;
      this.queryParams = {
        ...this.queryParams,
        deptId: this.deptId
      };
      pageSub(this.queryParams).then((response) => {
        const rows = response.rows;
        for (let i = 0; i < rows.length; i++) {
          this.$set(rows[i], "parentName", this.currentNode.label);
        }
        this.baQjDetailList = rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    getQjList() {
      qjList().then((response) => {
        this.qjList = response.data;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        detailId: undefined,
        qjId: undefined,
        remark: undefined,
        hh: undefined,
        delFlag: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined
      };
      this.resetForm("form");
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.$refs.addOrUpdateRef.init(null, this.queryParams.qjId);
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      const detailId = row.detailId || this.ids;
      this.$refs.addOrUpdateRef.init(detailId);
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const detailIds = row.detailId;
      this.$modal
        .confirm(`是否确认删除盒(筒)号${row.hh}？`)
        .then(() => {
          this.loading = true;
          return delBaQjDetail(detailIds);
        })
        .then(() => {
          this.loading = false;
          this.getDeptTree();
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {})
        .finally(() => {
          this.loading = false;
        });
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.$set(this.currentNode, "id", data.id);
      this.$set(this.currentNode, "label", data.label);
      if (!!data.children) {
        this.queryParams.parentId = data.id;
        this.getTreeList();
        this.oneShow = true;
        this.twoShow = false;
      } else {
        this.queryParams.qjId = data.id;
        this.getList();
        this.twoShow = true;
        this.oneShow = false;
      }
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "器具导入";
      this.upload.open = true;
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download("sycs/baQjDetail/importTemplate", {}, `baQjDetail_template_${new Date().getTime()}.xlsx`);
    }
  }
};
</script>
<style lang="scss" scoped>
@import "~@/assets/styles/demo.scss";
</style>
